package com.by.jdbc;


import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Statement;

/**
 * <p><p/>
 *
 * @author boyin
 * @ClassName ByH2Util
 * @Description H2数据库连接
 * @date 2024/12/24 6:28
 */
public abstract class ByJdbcUtil implements ByJdbcCommonInterface {
    private String jdbcType;

    private Connection connection;



    private ByJdbcUtil() {
    }

    public ByJdbcUtil(String jdbcType) {
        this.jdbcType = jdbcType;
        initMap();
        this.connection = createConnection();
    }

    /**
     * 读取properties文件
     */
    @Override
    public void initMap() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/jdbc.properties");
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void initSql(Connection connection) {
        initCreateSql(connection);
        initDataSql(connection);
    }

    private void initCreateSql(Connection connection){
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("sql/create.sql");
            byte[] bytes =new byte[inputStream.available()];
            inputStream.read(bytes);
            String sql =new String(bytes);
            String[] preSql = sql.split(";");
            Statement connectionStatement = connection.createStatement();
            for (String aSql : preSql) {
                aSql = aSql.trim();
                if (!aSql.isEmpty()) {
                    connectionStatement.execute(aSql);
                }
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private void initDataSql(Connection connection){
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("sql/data.sql");
            byte[] bytes =new byte[inputStream.available()];
            inputStream.read(bytes);
            String sql =new String(bytes);
            String[] preSql = sql.split(";");
            Statement connectionStatement = connection.createStatement();
            for (String aSql : preSql) {
                aSql = aSql.trim();
                if (!aSql.isEmpty()) {
                    connectionStatement.execute(aSql);
                }
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public String getJdbcType() {
        return jdbcType;
    }

    public void setJdbcType(String jdbcType) {
        this.jdbcType = jdbcType;
    }


    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }
}
